<svelte:options immutable={true} />

<script lang="ts">
  import { actixGraphqlEndpoint } from "$lib/js/stores";
  import { request, gql } from "graphql-request";

  import { useQuery } from "@sveltestack/svelte-query";

  import TaskQuizItem from "$lib/tasks/todo/TaskQuizItem.svelte";

  import type { KV, TaskType } from "$lib/ebm";

  export let attributes: KV[] = [
    {
      k: "subject",
      v: "en",
    },
  ];

  let endpoint = $actixGraphqlEndpoint;

  let subject: string = attributes.find((x) => x.k == "subject").v;

  const fetchTasks = async ({
    subject,
    recalltime = Math.floor(Date.now() / 1000),
    page = 0,
  }) => {
    const TASKS_QUERY = gql`
    query {
      tasks: listTasks(filter: { subject: { eq: "${subject}"} , ebpRecalltime:{ lt: ${recalltime} } }, page:${page}) {
        id
        snapshotAt
        subject
        title
        description
        assigneeId
        quizItemId
        ebpLastAt
        ebpTimesTotal
        ebpDifficulty
        ebpForgetproba
        ebpRecalltime
        createdAt
        updatedAt
        status
        from
        quizItem {
          id
          createdAt
          updatedAt
          title
          description
          stdAnswer
          opstype
          options {
            k
            v
          }
          master{
            id
            title
            description
          }
        }
      }
    }`;
    const { tasks } = await request(endpoint, TASKS_QUERY);
    //console.log("useQuery tasks=", tasks);
    return tasks;
  };

  let page = 0;
  let recalltime = Math.floor((Date.now() / 1000 / 60)) * 60 ;
  const tasksResult = useQuery<TaskType[], { message: string }>(
    ["tasks", { subject, recalltime, page }],
    () => fetchTasks({ subject, recalltime, page }),
    {
      enabled: !!endpoint,
    }
  );
</script>

<svelte:head>
  <title>TODO Ebbinghaus Tasks</title>
</svelte:head>

<div class="w-full flex flex-col items-center justify-center p-4 bg-gray-300">
  <div class="w-full p-4 bg-rose-50">
    <h1 class="left-0 text-left text-3xl">Todo Ebbinghaus Tasks</h1>
  </div>

  <div class="w-full items-center pt-4">
    {#if $tasksResult.isLoading}
      Loading...
    {:else if $tasksResult.isError}
      Error {$tasksResult.error}
    {:else}
      {#each $tasksResult.data as task, i (task.id)}
        <TaskQuizItem {task} index={i} />
      {/each}
    {/if}
  </div>
</div>
